package org.softmed.rest.server.defaults.handlers;

import groovy.lang.GroovyClassLoader;

import java.io.File;

import org.softmed.filehandling.FileUtil;
import org.softmed.groovy.utils.GroovyCache;
import org.softmed.rest.config.Handler;
import org.softmed.rest.server.core.handler.HandlerProcessParameters;
import org.softmed.rest.server.core.handler.IHandlerSolution;
import org.softmed.rest.server.core.handler.SpecificHandlerSolver;

import com.google.inject.Inject;

public class GroovyClassSolver implements SpecificHandlerSolver {
	FileUtil util = new FileUtil();

	@Inject
	GroovyCache groovyCache;

	boolean stop = false;

	@Override
	public boolean canSolve(Handler handler) {

		String path = handler.getPath();

		path = path.replace('.', '/');
		path += ".gc";

		// File file = util.getFile(path);
		// if (file == null || !file.exists())
		// return false;
		Class type = null;
		try {
			type = groovyCache.getGroovyClass(path);
		} catch (Throwable t) {
			// t.printStackTrace();
			return false;
		}

		return true;

	}

	@Override
	public void solve(Handler handler, HandlerProcessParameters parameters)
			throws Throwable {

		String path = handler.getPath();
		path = path.replace('.', '/');
		path += ".gc";

		File file = util.getFile(path);

		Class type = null;

		type = groovyCache.getGroovyClass(path);

		IHandlerSolution javaHandler = (IHandlerSolution) type.newInstance();
		javaHandler.solve(handler, parameters);
		stop = !javaHandler.isContinueProcessing();

	}

	@Override
	public boolean isContinueProcessing() {
		return !stop;
	}

	@Override
	public SpecificHandlerSolver getClone() {
		GroovyClassSolver clone = new GroovyClassSolver();
		clone.groovyCache = groovyCache;
		return clone;
	}

}
